package com.ybkj.daijia.api.gaode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.server.zhuan.SmallLocation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author zhyu
 * @date 2019-09-26 17:47:56
 */
@Component
public class GaodeApiRestTemplateImpl implements GaodeApi {

    private Logger logger = LoggerFactory.getLogger(GaodeApiRestTemplateImpl.class);
    @Autowired
    private RestTemplate restTemplate;
    private String word = null;

    public String getWord() {
        return word;
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public Integer createPath(String key, int sid, int clientId) {
        Map<String, Object> param = new HashMap<>();
        param.put("key", key);
        param.put("sid", sid);
        param.put("tid", clientId);
        try {
            String re = restTemplate.postForObject(CREATE_PATH, null, String.class, param);
            JSONObject jsonObject = JSON.parseObject(re);
            if (jsonObject != null) {
                if (jsonObject.containsKey(ERROR_CODE) && jsonObject.getInteger(ERROR_CODE)
                    .equals(SUCCESS_CODE)) {
                    JSONObject jsonObject1 = jsonObject.getJSONObject(DATA);
                    Integer integer = jsonObject1.getInteger(TRID);
                    return integer;
                } else {
                    if (logger.isErrorEnabled()) {
                        logger.error("高德获取里程失败, {}", jsonObject);
                    }
                }
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("create path error {}", e);
            }
        }
        return null;
    }

    @Override
    public boolean uploadLocations(List<SmallLocation> list, String key, int sid, int clientId,
        int tridId) {
        StringBuilder sb = new StringBuilder();
        boolean success = true;
        JSONObject jsonObject = null;
        Exception ee = null;
        try {
            for (int i = 0; i < list.size(); i++) {
                if (0 == i % MAX_POINT) {//0,99,198
                    sb.append("[");
                }
                if (i == list.size() - 1 || i % MAX_POINT == MAX_POINT - 1) {//98,
                    sb.append(list.get(i).printGD()).append("]");

                    MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
                    postParameters.add(TRID, String.valueOf(tridId));
                    postParameters.add(KEY, key);
                    postParameters.add(SID, String.valueOf(sid));
                    postParameters.add(TID, String.valueOf(clientId));
                    ;
                    postParameters.add(POINTS, sb.toString());
                    word = sb.toString();
                    HttpHeaders headers = new HttpHeaders();
                    headers.add("Content-Type", "application/x-www-form-urlencoded");
                    HttpEntity<MultiValueMap<String, Object>> r = new HttpEntity<>(postParameters,
                        headers);
                    String re = restTemplate.postForObject(UPLOAD_LOCATIONS, r, String.class);
                    jsonObject = JSON.parseObject(re);
                    if (re != null) {
                        if (jsonObject.containsKey(ERROR_CODE) && !jsonObject.getInteger(ERROR_CODE)
                            .equals(SUCCESS_CODE)) {
                            success = false;
                            break;
                        }
                    }
                    logger.info(sb.toString());
                    sb = new StringBuilder();
                } else {
                    sb.append(list.get(i).printGD()).append(",");
                }
            }
        } catch (Exception e) {
            ee = e;
            success = false;
        }
        if (!success) {
            if (logger.isErrorEnabled()) {
                logger.error("upload locations error, \nresponse {} \n error {}", jsonObject, ee);
            }
        }
        return success;
    }

    @Override
    public Double getDistance(String key, int sid, int clientId, int tridId, long startTime,
        long endTime) {
        Map<String, Object> param = new HashMap<>();
        param.put(KEY, key);
        param.put(SID, sid);
        param.put(TID, clientId);
        param.put(TRID, tridId);
        param.put(TID, clientId);
        param.put(STAR_TTIME, startTime);
        param.put(END_TIME, endTime);
        try {
            String re = restTemplate.postForObject(GET_DISTANCE, null, String.class, param);
            JSONObject jsonObject = JSON.parseObject(re);
            if (jsonObject != null) {
                if (jsonObject.containsKey(ERROR_CODE) && jsonObject.getInteger(ERROR_CODE)
                    .equals(SUCCESS_CODE)) {
                    JSONObject data = jsonObject.getJSONObject(DATA);
                    JSONArray jsonArray = data.getJSONArray(TRACKS);
                    if (0 < jsonArray.size()) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            if (obj.getInteger(TRID).equals(tridId)) {
                                Double dis = obj.getDouble(DISTANCE);
                                return dis;
                            }
                        }
                    }
                } else {
                    if (logger.isErrorEnabled()) {
                        logger.error("msg {}", re);
                    }
                }
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("get distance error {}", e);
            }
        }
        return null;
    }

    @Override
    public boolean deletePath(String key, int sid, int clientId, int trid) {
        Map<String, Object> param = new HashMap<>();
        param.put(KEY, key);
        param.put(SID, sid);
        param.put(TID, clientId);
        param.put(TRID, trid);
        try {
            String re = restTemplate.postForObject(DELETE_PATH, null, String.class, param);
            JSONObject jsonObject = JSON.parseObject(re);
            if (jsonObject != null) {
                if (jsonObject.containsKey(ERROR_CODE) && jsonObject.getInteger(ERROR_CODE)
                    .equals(SUCCESS_CODE)) {
                    return true;
                }
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("delete path error {}", e);
            }
        }
        word = null;
        return false;
    }
}
